package org.jetnuke.servlets.listeners;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.common.RequestListener;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.MessageDAO;
import org.jetnuke.entities.Message;
import org.jetnuke.repository.MessageRepository;

public class MessagesExpirationListener implements RequestListener {
	private final static Logger s_log = Logger.getLogger(MessagesExpirationListener.class);
	/* (non-Javadoc)
	 * @see org.jetnuke.common.RequestListener#request(javax.servlet.http.HttpServletRequest, org.apache.velocity.VelocityContext, org.jetnuke.common.IUserInfo, org.jetnuke.common.IAdminInfo, boolean, long)
	 */
	public void request(HttpServletRequest request, VelocityContext vc,
			IUserInfo iUserInfo, IAdminInfo iAdminInfo, boolean isIndex,
			long time) {
		try {
			MessageDAO mm=DataAccessDriver.getInst().newMessageDAO();
			List messageList = MessageRepository.getActiveMessages();//mm.selectActive();//messagePeer.doSelect(new Criteria().add(
					//messagePeer.ACTIVE, 1));
			Iterator it = messageList.iterator();
			while (it.hasNext()) {
				Message msg = (Message) it.next();
				int expire = msg.getEXPIRE();
				if (expire == 0)
					continue;
				GregorianCalendar gc = new GregorianCalendar();
				gc.setTime(msg.getDATE());
				gc.add(Calendar.SECOND, expire);
				if (gc.getTimeInMillis() < time) {
					it.remove();
					msg.setACTIVE(0);
					try {
						mm.update(msg);//msg.save();
						MessageRepository.clearCache();
					} catch (Exception e1) {
						s_log.error(e1);
					}
				}
			}
			vc.put("messages", messageList);
		} catch (Exception e) {
		}

	}

}
